package com.ruoyi.project.bajiaostar.user;


import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IpUtils;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aop.UserRepeatSubmit;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.bajiaostar.tGood.domain.TGood;
import com.ruoyi.project.bajiaostar.tGood.service.ITGoodService;
import com.ruoyi.project.bajiaostar.tGoodDetail.domain.TGoodDetail;
import com.ruoyi.project.bajiaostar.tGoodDetail.service.ITGoodDetailService;
import com.ruoyi.project.bajiaostar.tGoodOrder.domain.TGoodOrder;
import com.ruoyi.project.bajiaostar.user.dto.AdminLoginDto;
import com.ruoyi.project.bajiaostar.user.dto.GetGoodDetailByGoodIdDto;
import com.ruoyi.project.bajiaostar.user.dto.UpdateGoodNameDto;
import com.ruoyi.project.bajiaostar.user.dto.UpdateGoodStatusDto;
import com.ruoyi.project.bajiaostar.user.vo.ExportGoodDetailVo;
import com.ruoyi.project.system.user.service.IUserService;
import com.ruoyi.project.user.domain.TUser;
import com.ruoyi.project.user.entity.LoginByMobileReq;
import com.ruoyi.project.user.entity.UpdateUserPasswordReq;
import com.ruoyi.project.user.service.ITUserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户端登陆验证
 *
 */
@RestController
@RequestMapping("/nt/good")
@Slf4j
public class WebGoodController extends BaseController {

    @Autowired
    ITGoodService  goodService;
    @Autowired
    ITGoodDetailService goodDetailService;



    @ApiOperation("修改商品状态")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/updateGoodStatus")
    @UserRepeatSubmit
    public AjaxResult updateGoodStatus (@RequestBody UpdateGoodStatusDto req, HttpServletRequest request) {
        try {
            if(ObjectUtils.isEmpty(req)){
                return AjaxResult.error("信息有误,请检查");
            }
            TGood good=new TGood();
            good.setId(req.getId());
            good.setGoodStatus(req.getGoodStatus());
            goodService.updateTGood(good);
            return AjaxResult.success();
        } catch (Exception e) {
            return this.error("修改商品状态失败 " + e.getMessage());
        }
    }

    @ApiOperation("修改商品名称")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/updateGoodName")
    @UserRepeatSubmit
    public AjaxResult updateGoodName (@RequestBody UpdateGoodNameDto req, HttpServletRequest request) {
        try {
            if(ObjectUtils.isEmpty(req)){
                return AjaxResult.error("信息有误,请检查");
            }
            if(ObjectUtils.isEmpty(req.getGoodId()) || ObjectUtils.isEmpty(req.getGoodName())){
                return AjaxResult.error("请检查修改信息已填写");
            }
            TGood good=new TGood();
            good.setId(req.getGoodId());
            good.setGoodName(req.getGoodName());
            good.setGoodFileUrl(req.getGoodFileUrl());
            goodService.updateTGood(good);
            return AjaxResult.success();
        } catch (Exception e) {
            return this.error("修改商品名称失败 " + e.getMessage());
        }
    }
    @ApiOperation("分页查询商品")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/list")
    @UserRepeatSubmit
    public TableDataInfo list(@RequestBody TGood tGood)
    {
        startPage(tGood.getPageNum(),tGood.getPageSize());
        List<TGood> list = goodService.selectTGoodList(tGood);
        return getDataTable(list);
    }

    @ApiOperation("根据商品获取所有在售日期")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/getGoodDetailDateByGoodId/{goodId}")
    @UserRepeatSubmit
    public AjaxResult getGoodDetailDateByGoodId(@PathVariable("goodId")Long goodId)
    {
        List<String> list = goodDetailService.getGoodDetailDateByGoodId(goodId);
        return AjaxResult.success(list);
    }

    @ApiOperation("根据商品id与时间分页查询规格")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/getGoodDetailByGoodId")
    @UserRepeatSubmit
    public TableDataInfo getGoodDetailByGoodId(@RequestBody GetGoodDetailByGoodIdDto dto)
    {
        startPage(dto.getPageNum(),dto.getPageSize());
        List<TGoodDetail> list = goodDetailService.getGoodDetailByGoodId(dto);
        return getDataTable(list);
    }

    @ApiOperation("根据商品下载数据")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @GetMapping("/exportGoodDetailByGoodId/{goodId}")
    @UserRepeatSubmit
    public AjaxResult exportGoodDetailByGoodId(@PathVariable("goodId")Long goodId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        TGoodDetail detail=new TGoodDetail();
        detail.setGoodId(goodId);
        List<TGoodDetail> tGoodDetails = goodDetailService.selectTGoodDetailList(detail);
        List<ExportGoodDetailVo>  list=new ArrayList();
        for (TGoodDetail detail1:tGoodDetails) {
            ExportGoodDetailVo vo=new ExportGoodDetailVo();
            BeanUtil.copyProperties(detail1,vo);
            vo.setGoodDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,detail1.getGoodDate()));
            list.add(vo);
        }
        //获取商品信息
        TGood good = goodService.selectTGoodById(goodId);
        if(ObjectUtils.isEmpty(good)){
            return AjaxResult.error("商品信息有误,请刷新后查看");
        }

        ExcelUtil<ExportGoodDetailVo> util = new ExcelUtil<ExportGoodDetailVo>(ExportGoodDetailVo.class);
        //http://127.0.0.1/common/download?fileName=8fcc83d5-6d4a-4f7a-943d-7a6d36b85cfe_%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1.xlsx&delete=true
        AjaxResult ajaxResult = util.exportExcel(list, "exportGoodDetail" + goodId,good.getGoodName());
       String fileName= ajaxResult.get("msg")+"";
        if (!ObjectUtils.isEmpty(fileName)){
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());

    }
        return  AjaxResult.success("成功",ajaxResult.get("msg"));
    }


    @ApiOperation("用户根据商品id获取商品详情发送到邮箱")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @GetMapping("/sendGoodDetail/{goodId}")
    @UserRepeatSubmit
    public AjaxResult sendGoodDetail(@PathVariable("goodId")Long goodId)
    {
        Long appUserId = getAppUserId();
        Thread thread = new Thread(() -> {
            log.info("用户根据商品id获取商品详情发送到邮箱开始");
            goodDetailService.sendGoodDetail(goodId,appUserId);
            log.info("用户根据商品id获取商品详情发送到邮箱结束");
        });
        thread.start();
        return  AjaxResult.success("详情已发送至邮箱,请稍后到邮箱查看");
    }

    @ApiOperation("获取所有上架商品")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/findAllList")
    @UserRepeatSubmit
    public AjaxResult findAllList( )
    {
        TGood tGood =new TGood();
        tGood.setGoodStatus(0);
        List<TGood> list = goodService.selectTGoodList(tGood);
        return AjaxResult.success(list);
    }

    @ApiOperation("获取所有上架商品(包含下架商品)")
    @Log(title = "APP接口管理", businessType = BusinessType.OTHER)
    @PostMapping("/findAllGoodList")
    @UserRepeatSubmit
    public AjaxResult findAllGoodList()
    {
        TGood tGood =new TGood();
        List<TGood> list = goodService.selectTGoodList(tGood);
        return AjaxResult.success(list);
    }

}
